package com.fh.shop.api.sms.biz;

import com.alibaba.fastjson.JSON;
import com.fh.shop.api.common.ResponseEnum;
import com.fh.shop.api.common.ServerResponse;
import com.fh.shop.api.common.SystemConst;
import com.fh.shop.api.sms.mapper.ISMSMapper;
import com.fh.shop.api.sms.vo.SMSVo;
import com.fh.shop.api.util.KeyUtil;
import com.fh.shop.api.util.RedisUtil;
import com.fh.shop.api.util.SMSUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("smsService")
public class ISMSServiceImpl implements ISMSService {

    @Autowired
    private ISMSMapper smsMapper;

    //判断 验证码
    @Override
    public ServerResponse sendMsg(String phone) {
        //验证手机号是否为空
        if (StringUtils.isEmpty(phone)){
            return ServerResponse.error(ResponseEnum.SMS_PHONE_IS_NULL);
        }
        //-- 验证手机号 格式是否正确 -- 暂时没有

        String result = SMSUtil.sendMsg(phone);
        //将json格式的字符串转换为java对象
        SMSVo smsVo = JSON.parseObject(result, SMSVo.class);
        int code = smsVo.getCode();
        if (code == SystemConst.SMS_OK){
            //短信验证码
            String obj = smsVo.getObj();
            //将短信验证码存入redis中 缓存服务器 ,方便后续的对比验证
            RedisUtil.setEx(KeyUtil.buildSMSPhoneKey(phone),obj,SystemConst.SMS_CODE_EXPIRE_TIME);
            return ServerResponse.success();
        }else {
            return ServerResponse.error(-1,"发送验证码失败，错误编号："+code+",请 联系管理员");
        }


    }
}
